﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using ToolUtil;
using zyconfig;
using zymarc;

namespace zymain
{
    public partial class FrmZrt : Form
    {
        public string wxlx="待采书库";
        public DataTable dt = new DataTable();
        private List<string> mlist = new List<string>();
        public BindingSource BookData;
        private string mainKay;
        public string uid;
        public int gjm;
        public FrmZrt()
        {
            InitializeComponent();
        }

        private void FrmZrt_Load(object sender, EventArgs e)
        {
            using (DbOperHandler _open = new Common().Doh())
            {
                _open.Reset();
                _open.SqlCmd = "SELECT COLUMN_NAME as cname,DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME not like '%键码%' AND TABLE_NAME = '" + wxlx + "'";
                DataTable zdt = _open.GetDataTable();
                foreach (DataRow drow in zdt.Rows)
                {
                    this.kxzdList.Items.Add(drow["cname"]);
                }

                _open.Reset();
                _open.SqlCmd = "select 序号,报表名称,所属模块 ,操作员 from 自定义导出报表 where 所属模块='" + wxlx + "'";
                DataTable dr = _open.GetDataTable();
                this.BookData = new BindingSource();
                this.dataGridBlist.AutoGenerateColumns = false;
                this.BookData.DataSource = dr;
                this.BookData.PositionChanged += new EventHandler(this.BookData_PositionChanged);
                this.dataGridBlist.DataSource = this.BookData;
                if(this.BookData.Count>0)
                    this.BookData_PositionChanged(sender, e);
               
            }
        }
        private void BookData_PositionChanged(object sender, EventArgs e)
        {
            this.yxzdList.Items.Clear();
            for (int i = kxzdList.Items.Count - 1; i > -1; i--)
            {
                kxzdList.SetItemChecked(i, false);
            }
            this.mlist.Clear();
            DataRowView current = this.BookData.Current as DataRowView;
            this.mainKay = current["序号"].ToString().Trim();
            using (DbOperHandler _open = new Common().Doh())
            {
                _open.Reset();
                _open.ConditionExpress = "序号="+mainKay;
                try
                {
                    string zbz = _open.GetField("自定义导出报表", "备注").ToString().Trim();
                    if (!string.IsNullOrEmpty(zbz))
                    {
                        string[] zbzs = Regex.Split(zbz, "\n");
                        foreach (string str in zbzs)
                        {
                            if (!string.IsNullOrEmpty(str))
                            {
                                string[] zbzs1 = str.Split(';');
                                int zs = (zbzs1.Length - 1) / 6;
                                for (int i = 0; i < zs; i++)
                                {
                                    if (zbzs1[i * 6 + 3].Equals("-1"))
                                    {
                                        for (int k = 0; k < kxzdList.Items.Count; k++)
                                        {
                                            if (kxzdList.Items[k].ToString().Trim().Equals(zbzs1[i * 6 + 1]))
                                            {
                                                //if (!kxzdList.GetItemChecked(k))
                                                //{
                                                //    kxzdList.SetItemChecked(k, true);
                                                //}
                                                kxzdList.SetItemChecked(k, true);
                                                //this.yxzdList.Items.Add(zbzs1[i * 6 + 1]);
                                            }
                                        }
                                    }
                                    if (zbzs1[i * 6 + 3].Equals("0"))
                                    {
                                        this.yxzdList.Items.Add(zbzs1[i * 6 + 1]);
                                        mlist.Add(zbzs1[i * 6 + 1] + ";" + zbzs1[i * 6 + 4]);
                                    }
                                    //for (int j = 0; j < 6; j++)
                                    //{
                                    //    Console.WriteLine(zbzs1[i*6+j] + "::" + zbzs1.Length);
                                    //}
                                }
                            }
                        }
                        if (this.yxzdList.Items.Count > 0)
                            this.yxzdList.SelectedIndex = this.yxzdList.Items.Count - 1;
                    }
                }
                catch { }
                
                
            }
            this.kxzdList.SelectionMode = SelectionMode.None;
            this.saveBtn.Enabled = false;
            this.xjmBtn.Enabled = false;
            this.bcmBtn.Enabled = false;
            this.scmBtn.Enabled = false;

        }
        private void kxzdList_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            // 当项的选中状态发生改变时触发的事件
            string selectedOption = kxzdList.Items[e.Index].ToString();
            //bool isChecked = (e.NewValue == CheckState.Checked);
            //MessageBox.Show(selectedOption + " 的选中状态改变为：" + isChecked);
            if(e.NewValue == CheckState.Checked)
            {
                this.yxzdList.Items.Add(selectedOption);
            }
            else
            {
                this.yxzdList.Items.Remove(selectedOption);
            }
            if (this.yxzdList.Items.Count > 0)
                this.yxzdList.SelectedIndex = this.yxzdList.Items.Count - 1;
        }

        private void kxzdList_SelectedIndexChanged1(object sender, EventArgs e)
        {
            this.yxzdList.Items.Clear();
            //string selectedOptions = string.Empty;
            foreach (var item in kxzdList.CheckedItems)
            {
                //selectedOptions += item.ToString() + Environment.NewLine;
                this.yxzdList.Items.Add(item.ToString());
            }
            if (this.yxzdList.Items.Count > 0)
                this.yxzdList.SelectedIndex = this.yxzdList.Items.Count - 1;
            //MessageBox.Show("选中的项有：" + Environment.NewLine + selectedOptions);
        }

        private void yxzd_SelectedIndexChanged(object sender, EventArgs e)
        {
            dataGridBook.ColumnCount = yxzdList.Items.Count;
            dataGridBook.RowHeadersVisible = false;
            for (int i = 0; i < yxzdList.Items.Count; i++)
            {
                dataGridBook.Columns[i].Name = i+"yxzd";
                //dataGridBook.Columns[i].DataPropertyName = yxzdList.Items[i].ToString().Trim();
                dataGridBook.Columns[i].HeaderText = yxzdList.Items[i].ToString().Trim(); //显示名称
            }
            foreach(string str in mlist){
                if (this.yxzdList.SelectedIndex > 0)
                {
                    if (str.StartsWith(this.yxzdList.SelectedItem.ToString()))
                    {
                        string mzd = str.Split(';')[1];
                        this.zdTxt.Text = mzd.Split('\x001f')[0];
                        this.zzdTxt.Text = mzd.Split('\x001f')[1];
                        this.fgfTxt.Text = mzd.Split('\x001f')[2];
                        this.xnameTxt.Text = str.Split(';')[0];
                        //this.saveBtn.Enabled = true;
                        this.xjmBtn.Enabled = true;
                        if (kxg)
                        {
                            this.bcmBtn.Enabled = true;
                            this.scmBtn.Enabled = true;
                        }
                        break;
                    }
                }
            }
            if (this.dt.Rows.Count > 0)
            {
                if(this.dt.Rows.Count>3)
                    this.dataGridBook.RowCount = 3;
                else
                    this.dataGridBook.RowCount = this.dt.Rows.Count;
            }

        }
        private bool IsPartiallyVisible(DataGridView gridView, DataGridViewCellValueEventArgs e)
        {
            if (gridView.FirstDisplayedScrollingColumnIndex == e.ColumnIndex)
            {
                if (gridView.FirstDisplayedScrollingColumnHiddenWidth != 0)
                {
                    return true;
                }
            }
            bool sameWidth = gridView.GetColumnDisplayRectangle(e.ColumnIndex, false).Width == gridView.GetColumnDisplayRectangle(e.ColumnIndex, true).Width;
            return !sameWidth;
        }

        private void dgvbook_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e)
        {
            if (e.RowIndex == this.dataGridBook.RowCount)
            {
                return;
            }
            else
            {
                if (!IsPartiallyVisible(this.dataGridBook, e))
                {
                    string colName = this.dataGridBook.Columns[e.ColumnIndex].HeaderText;
                    //Console.WriteLine(colName + ":;;;;");
                    if (!string.IsNullOrEmpty(colName))
                    {
                        if (this.dt.Columns.Contains(colName))
                        {
                            //Console.WriteLine(this.dt.Columns[colName].DataType);
                            this.dataGridBook.Columns[e.ColumnIndex].ValueType = this.dt.Columns[colName].DataType;
                            switch (dt.Columns[colName].DataType.Name)
                            {
                                case "String":
                                    e.Value = this.dt.Rows[e.RowIndex][colName].ToString().Trim();
                                    break;
                                case "Boolean":
                                    string st = this.dt.Rows[e.RowIndex][colName].ToString().Trim();
                                    if (st.Length == 0)
                                        e.Value = false;
                                    else
                                        e.Value = Convert.ToBoolean(this.dt.Rows[e.RowIndex][colName].ToString().Trim());
                                    break;
                                case "Decimal":
                                    try
                                    {
                                        e.Value = Convert.ToDecimal(this.dt.Rows[e.RowIndex][colName].ToString().Trim());
                                    }
                                    catch { e.Value = 0; }
                                    break;
                                case "Int32":
                                    try
                                    {
                                        e.Value = Convert.ToInt32(this.dt.Rows[e.RowIndex][colName].ToString().Trim());
                                    }
                                    catch { e.Value = 0; }
                                    break;
                            }
                        }
                        else
                        {
                            string colContent = "", marc = "";
                            Type tt = typeof(string);
                            using (DbOperHandler _open = new Common().Doh())
                            {
                                _open.Reset();
                                _open.ConditionExpress = "键码=" + this.dt.Rows[e.RowIndex]["键码"].ToString().Trim();
                                try
                                {
                                    marc = _open.GetField(wxlx, "MARC").ToString();
                                    if (kxzdList.Items.Contains(colName))
                                    {
                                        colContent = _open.GetField(wxlx, colName).ToString().Trim();
                                        tt = _open.GetField(wxlx, colName).GetType();
                                    }
                                }
                                catch { }
                            }
                            if (string.IsNullOrEmpty(colContent))
                            {
                                foreach (string str in mlist)
                                {
                                    //Console.WriteLine(str+"::"+colName);
                                    //Console.WriteLine(marc);
                                    if (str.StartsWith(colName) && !string.IsNullOrEmpty(marc))
                                    {
                                        string mzd = str.Split(';')[1];
                                        MarcConvert convert = new MarcConvert();
                                        convert.MarcText = marc;
                                        //Console.WriteLine(mzd.Split('\x001f')[0] + "::" + mzd.Split('\x001f')[1] + convert.GetASubField(mzd.Split('\x001f')[0], mzd.Split('\x001f')[1], 1));
                                        e.Value = convert.GetASubField(mzd.Split('\x001f')[0], mzd.Split('\x001f')[1], 1);
                                        this.dataGridBook.Columns[e.ColumnIndex].ValueType = typeof(string);
                                    }
                                }
                            }
                            else
                            {
                                e.Value = colContent;
                                this.dataGridBook.Columns[e.ColumnIndex].ValueType = tt;
                            }
                        }
                    }
                }
                else
                    return;
            }
        }

        private void expBtn_Click(object sender, EventArgs e)
        {
            this.dataGridBook.Rows.Clear();
            if (this.dt.Rows.Count > 0)
            {
                this.dataGridBook.RowCount = this.dt.Rows.Count;
            }
            OfficeTool.DgvToExcel(this.dataGridBook);
        }

        private void dgvbook_CellValuePushed(object sender, DataGridViewCellValueEventArgs e)
        {
            Console.WriteLine(dataGridBook.Rows[e.RowIndex].Cells[e.ColumnIndex].Value);
        }
        private bool kxg = false,xjm=false;
        private void mdifBtn_Click(object sender, EventArgs e)
        {
            this.kxzdList.SelectionMode = SelectionMode.One;
            this.saveBtn.Enabled = true;
            this.xjmBtn.Enabled = true;
            kxg = true;
        }
        private void saveBbs()
        {
            string bznr = "";
            for (int i = 0; i < yxzdList.Items.Count; i++)
            {
                string colname = yxzdList.Items[i].ToString().Trim();
                if (this.kxzdList.Items.Contains(colname))
                {
                    bznr += "ADOBibData;" + colname + ";;-1;;100;\n";
                }
                else
                {
                    foreach (string str in mlist)
                    {
                        if (str.StartsWith(colname))
                        {
                            string mzd = str.Split(';')[1];
                            bznr += "ADOBibData;" + colname + ";;0;" + mzd + ";100;\n";
                        }
                    }
                }
            }
            //Console.WriteLine(bznr);
            if (!string.IsNullOrEmpty(bznr))
            {
                using (DbOperHandler _open = new Common().Doh())
                {
                    _open.Reset();
                    _open.ConditionExpress = "序号=" + this.mainKay;
                    _open.AddFieldItem("备注", bznr);
                    _open.Update("自定义导出报表");
                }
            }
        }
        private void saveBtn_Click(object sender, EventArgs e)
        {
            this.saveBbs();
        }

        private void syBtn_Click(object sender, EventArgs e)
        {
            ListBoxTool.MoveSelectedItemUp(this.yxzdList);
        }

        private void xyBtn_Click(object sender, EventArgs e)
        {
            ListBoxTool.MoveSelectedItemDown(this.yxzdList);
        }

        private void xjmBtn_Click(object sender, EventArgs e)
        {
            /**
            this.zdTxt.Text = "";
            this.zzdTxt.Text = "";
            this.fgfTxt.Text = "";
            this.xnameTxt.Text = "";
            **/
            xjm = true;
            this.bcmBtn.Enabled = true;
            if (string.IsNullOrEmpty(this.zdTxt.Text.Trim()))
                this.zdTxt.Focus();
            else
                this.xnameTxt.Focus();
        }

        private void scmBtn_Click(object sender, EventArgs e)
        {
            string xname = this.xnameTxt.Text.Trim();
            if (string.IsNullOrEmpty(xname))
            {
                ShowMessageBox.ShowMessageBoxTimeout("显示名称不能为空！", "警告", MessageBoxButtons.OK, 2000);
                this.xnameTxt.Focus();
            }
            else
            {
                for (int i = 0; i < mlist.Count; i++)
                {
                    if (mlist[i].Split(';')[0].Equals(xname))
                    {
                        mlist.RemoveAt(i);
                        break;
                    }
                }
                if (yxzdList.SelectedIndex >= 0 && yxzdList.Items[yxzdList.SelectedIndex].Equals(xname))
                    yxzdList.Items.RemoveAt(yxzdList.SelectedIndex);
            }
        }

        private void exitBtn_Click(object sender, EventArgs e)
        {
            base.Close();
        }

        private void newBtn_Click(object sender, EventArgs e)
        {
            using (DbOperHandler _open = new Common().Doh())
            {
                _open.Reset();
                int mid =_open.MaxValue("自定义导出报表", "序号");
                DataRowView newRowView = BookData.AddNew() as DataRowView;
                this.mainKay = (mid + 1).ToString();
                newRowView["序号"] = mid+1;
                newRowView["报表名称"] = "报表名"+ this.mainKay;
                newRowView["所属模块"] = "待采书库";
                newRowView["操作员"] = 1;
                BookData.EndEdit();
            }
        }

        private void dgvbl_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            DataGridViewRow row = dataGridBlist.Rows[e.RowIndex];
            DataGridViewCell cell = row.Cells[e.ColumnIndex];
            // 获取当前编辑的单元格的值
            string value = cell.Value.ToString();
            //Console.WriteLine("但钱单元格" + value);
            using (DbOperHandler _open = new Common().Doh())
            {
                _open.Reset();
                _open.ConditionExpress = "序号=" + this.mainKay;
                if (_open.Exist("自定义导出报表"))
                {
                    _open.AddFieldItem("报表名称", value);
                    _open.AddFieldItem("操作员", this.uid);
                    _open.AddFieldItem("馆键码", this.gjm);
                    _open.AddFieldItem("字体", "宋体;clBlack;9;-12;0000" + '\x001e'.ToString() + "宋体;clBlack;9;-12;0000" + '\x001e'.ToString() + "宋体;clBlack;9;-12;0000");
                    _open.AddFieldItem("页面设置", "10;10;10;10");
                    _open.AddFieldItem("所属模块", "待采书库");
                    _open.AddFieldItem("纸张宽度", 210);
                    _open.AddFieldItem("纸张高度", 297);
                    _open.Update("自定义导出报表");
                }
                else
                {
                    _open.Reset();
                    _open.AddFieldItem("报表名称", value);
                    _open.AddFieldItem("操作员", this.uid);
                    _open.AddFieldItem("馆键码", this.gjm);
                    _open.AddFieldItem("字体", "宋体;clBlack;9;-12;0000" + '\x001e'.ToString() + "宋体;clBlack;9;-12;0000" + '\x001e'.ToString() + "宋体;clBlack;9;-12;0000");
                    _open.AddFieldItem("页面设置", "10;10;10;10");
                    _open.AddFieldItem("所属模块", "待采书库");
                    _open.AddFieldItem("纸张宽度", 210);
                    _open.AddFieldItem("纸张高度", 297);
                    this.mainKay = _open.Insert("自定义导出报表").ToString();
                }
                
            }
            this.saveBbs();
        }

        private void bcmBtn_Click(object sender, EventArgs e)
        {
            string xnr = this.zdTxt.Text + '\x001f'.ToString() + this.zzdTxt.Text + '\x001f'.ToString() + this.fgfTxt.Text;
            string xname = this.xnameTxt.Text.Trim();
            string zd = this.zdTxt.Text.Trim();
            string zzd = this.zzdTxt.Text.Trim();
            if (string.IsNullOrEmpty(zd))
            {
                ShowMessageBox.ShowMessageBoxTimeout("字段不能为空！", "警告", MessageBoxButtons.OK, 2000);
                this.zdTxt.Focus();
                return;
            }
            if (string.IsNullOrEmpty(zzd))
            {
                ShowMessageBox.ShowMessageBoxTimeout("子字段不能为空！", "警告", MessageBoxButtons.OK, 2000);
                this.zzdTxt.Focus();
                return;
            }
            if (string.IsNullOrEmpty(xname))
            {
                ShowMessageBox.ShowMessageBoxTimeout("显示名称不能为空！", "警告", MessageBoxButtons.OK, 2000);
                this.xnameTxt.Focus();
            }
            else
            {
                if (xjm)
                {
                    //Console.WriteLine(this.yxzdList.Items.Contains(xname) + ":::" + xname);
                    if (!this.yxzdList.Items.Contains(xname))
                    {
                        mlist.Add(xname + ";" + xnr);
                        this.yxzdList.Items.Add(xname);
                        if (this.yxzdList.Items.Count > 0)
                            this.yxzdList.SelectedIndex = this.yxzdList.Items.Count - 1;
                    }                    
                }
                else
                {
                    if (yxzdList.SelectedIndex >= 0) { 
                        string colname = this.yxzdList.SelectedItem.ToString();
                        if (!string.IsNullOrEmpty(colname))
                        {
                            for (int i = 0; i < mlist.Count; i++)
                            {
                                if (mlist[i].Split(';')[0].Equals(colname))
                                {
                                    mlist[i] = xname + ";" + xnr;
                                    break;
                                }
                            }
                            yxzdList.Items[yxzdList.SelectedIndex] = xname;
                        }
                    }
                }
            }
            this.saveBtn_Click(sender, e);
            if (this.yxzdList.Items.Count > 0)
                this.yxzdList.SelectedIndex = this.yxzdList.Items.Count - 1;
        }
    }
}
